import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'dart:js' as js;
import 'dart:convert' as convert;
class FreshERPPage extends StatefulWidget {
  @override
  CoordinatorLayoutTestPageState createState() =>
      new CoordinatorLayoutTestPageState();
}

class CoordinatorLayoutTestPageState extends State<FreshERPPage> {
  List<String> items = ["1", "2", "3", "4", "5", "6", "7", "8"];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    items.add((items.length + 1).toString());
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  var jsonDecode=convert.jsonDecode("[]");
  @override
  void initState() {
    super.initState();
    Future<String> loadString =
    DefaultAssetBundle.of(context).loadString("data/erp_function.json");
    loadString.then((value) {
      String st = value;

      setState(() {
        jsonDecode = convert.jsonDecode(st);
        print(jsonDecode.length);
      });
//      print(jsonDecode);
//      print(jsonDecode[0]);
//      print(jsonDecode[0]["key"]);
    });
  }

  @override
  Widget build(BuildContext context) {
    var ss = js.context["browser"];
    if (ss != null) {
      js.context["browser"].callMethod("setBrowser", [
        "{\"showToolbar\": \"false\",\"fullScreen\": \"true\",\"autoCloseable\": \"false\",\"showRefresh\": \"false\" }"
      ]);
    }
    return Scaffold(
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: false,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("上拉加载");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！点击重试！");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("松手,加载更多!");
            } else {
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: CustomScrollView(
          scrollDirection: Axis.vertical,
          slivers: <Widget>[
            _bar(),
            //单个控件
//                _head(),
          _gridHeadList(),
            //List
            _list(),
            //GridList
            _gridList(),
          ],
        ),
      ),
    );
  }

  /// grid
  SliverPadding _gridList() {
    return SliverPadding(
      padding: EdgeInsets.only(left: 10.0, bottom: 20, right: 10.0),
      sliver: SliverGrid(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
           ////一行多少个
            crossAxisCount: 2,
            //宽高比
            childAspectRatio:6,
            //// 上下间隔
            mainAxisSpacing: 1,
            //// 左右间隔
            crossAxisSpacing: 1.0),
           delegate: SliverChildBuilderDelegate(
          (BuildContext context, int index) {

            return getItemContainer(index);
          },
          childCount: 5,
        ),
      ),
    );
  }
  ///grid内容
  Widget getItemContainer(int index) {
    return         Card(child:
    Center(
        child:
        Column(
          mainAxisAlignment:MainAxisAlignment.center,//设置居中
          children: [
            Text(items[index]),
            Image.asset('images/icon_outlets_order_home.png', fit: BoxFit.cover,height: 30,)
          ],
        )));
    return Container(
      height: 10,
      alignment: Alignment.center,
      child:
      Text(
        'grid title $index',
        style: TextStyle(color: Colors.white, fontSize: 20),
      ),
      color: Colors.blue,
    );
  }

  ///list
  SliverFixedExtentList _list() {
    return SliverFixedExtentList(
        delegate: SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            return _liveRemainContent(index);
          },
          childCount: 5,
        ),
        itemExtent: 48.0);
  }

  ///list Item
  Widget _liveRemainContent(int index) {
    return Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(left: 20.0, right: 20.0),
          padding: EdgeInsets.all(3.0),
          decoration: BoxDecoration(
              color: Colors.white,
              shape: BoxShape.rectangle,
              borderRadius: BorderRadius.circular(3.0),
              border: Border.all(color: Colors.grey, width: 0.5)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Image.asset('images/icon_outlets_order_home.png', fit: BoxFit.cover,height: 30,),
                  Text('我的标题$index', style:  TextStyle(fontSize: 17.0, color: Colors.blueAccent))
                ],
              ),
            ],
          ),
        ),
        SizedBox(height: 10)
      ],
    );
  }



  SliverPadding   _gridHeadList() {
    return
      SliverPadding(
      padding: EdgeInsets.only(   ),

      sliver:        SliverGrid(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: jsonDecode.length,
            childAspectRatio: 8.0,
            mainAxisSpacing: 1.0,
            crossAxisSpacing: 1.0),
         delegate: SliverChildBuilderDelegate(   (BuildContext context, int index) {
          return getHeadItem(index);
        },
          childCount: jsonDecode.length,
        ),
      ),


    );
  }

  ///grid内容
  Widget getHeadItem(int index) {
    print(jsonDecode[index]["icon"]);
    return Container(
      height: 0 ,
      color: Colors.white,
      alignment: Alignment.center,
        child:
        Column(       crossAxisAlignment: CrossAxisAlignment.start,
            children:[
//          Image.asset(jsonDecode[index]["icon"]   ),
          Text(
            jsonDecode[index]["key"].toString(),
            style: TextStyle(color: Colors.black, fontSize: 20),
          )
        ]
     ),
    );

  }

  ///head
  SliverToBoxAdapter _head() {
    // 将单个控件放入CustomScroView中
    return SliverToBoxAdapter(
      child: Container(
        height: 50.0,
        margin: EdgeInsets.all(10.0),
        padding: EdgeInsets.only(left: 10.0, right: 10.0),
        alignment: Alignment.center,
        decoration: BoxDecoration(color: Colors.green),
      ),
    );
  }

  ///appBar
  Widget _bar() {
    return SliverAppBar(
      toolbarHeight: 100,
      primary: true,
//     leading: Icon(null),//导航箭头
      automaticallyImplyLeading: false,
      pinned: true,
      expandedHeight: 250.0,
      // title: Text('SliverAppBar'),
      flexibleSpace: FlexibleSpaceBar(
//       titlePadding: EdgeInsets.only(top: 0),
        // titlePadding: EdgeInsets.all(15),
        title: Text('标题d'),
        collapseMode: CollapseMode.parallax,
        background: Image.asset('images/bg_work.jpg', fit: BoxFit.cover),
      ),
      backgroundColor: Theme.of(context).accentColor,
      actions: <Widget>[
      ],
      elevation: 10.0,
      forceElevated: true,
    );



  }
}
